package com.kexun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kexun.utils.Result;
import com.kexun.webSocket.MessageHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("message")
public class MessageController {

    @Autowired
    private MessageHandler messageHandler;

    private static Logger logger = Logger.getLogger(MessageController.class);

    @RequestMapping("retrySend")
    public Result retrySend(@RequestBody String req) {
        logger.info("收到其他服务的推送");
        JSONObject reqJson = JSON.parseObject(req);
        String token = reqJson.getString("token");
        if (StringUtils.isEmpty(token)) {
            return Result.error("token不能为空");
        }
        if (!token.equals("0c8534b8a5a54f7a9a4fe7581cb97d63")) {
            return Result.error("token无效");
        }
        String userId = reqJson.getString("userId");
        String message = reqJson.getString("message");
        messageHandler.retrySendMessage(userId, message);
        return Result.success();
    }


    @RequestMapping("send")
    public String send(@RequestBody String req) {
        JSONObject reqJson = JSON.parseObject(req);
        String token = reqJson.getString("token");
        if (StringUtils.isEmpty(token)) {
            return "token不能为空";
        }
        if (!token.equals("0c8534b8a5a54f7a9a4fe7581cb97d63")) {
            return "token无效";
        }
        String to = reqJson.getString("to");
        String content = reqJson.getString("content");
        messageHandler.sendMessage(to, content);
        return "消息发送成功";
    }

}
